<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
use Crypt;

class LoginController extends Controller
{
    //显示登录页面
    public function login(Request $request)
    {
        if($request -> isMethod('POST'))
        {   
            //检测cookie有没有值
            $isLogin = \Cookie::get('isLogin');
            if($isLogin)
            {   
                $res = DB::table('users') -> select('users.*', 'users_info.pic') -> leftJoin('users_info', 'users.id', '=', 'users_info.user_id') -> first();

                Session::put('master', $res);
                return redirect('/admin/index') -> with(['info' => '登陆成功']);
            }

            //表单显示帐号
            $request -> flashOnly('email');

            //验证码
            $code = $request -> input('code');
            if($code != Session::get('code'))
            {
                return back() -> with(['info' => '验证码错误']);
            }

            // 验证邮箱和密码
            $email = $request -> input('email');
            $res = DB::table('users') -> select('users.*', 'users_info.pic') -> leftJoin('users_info', 'users.id', '=', 'users_info.user_id') -> first();
            if(!$res)
            {
                return back() -> with(['info' => '用户名不正确']);
            }

            //解密
            $password = Crypt::decryptString($res -> password);
            if($request -> input('password') != $password)
            {
                return back() -> with(['info' => '用户名或者密码错误']);
            }

            //判断是否记住我
            if($request -> has('checkMe'))
            {
                \Cookie::queue('isLogin', $res -> name, 60);
            }

            Session::put('master', $res);
            return redirect('/admin/index') -> with(['info' => '登陆成功']);
        }else
        {
            return view('admin.login.index', ['title' => '登录']);
        }

        
    }

    //用户退出设置
    public function logout()
    {
        Session::forget('master');
        return redirect('/admin/login') -> with(['info' => '退出成功']);
    } 
    
}
